/*
 * Copyright (C) 2008  Young,Fey <fey.young@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */ 

package com.youngfey.wordmaster.database

import groovy.sql.Sql
import org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource40
import com.youngfey.wordmaster.database.tables.*
//import com.youngfey.wordmaster.database.views.*

public class Database {
    static final NAME = "${System.getProperty('user.home')}${System.getProperty('file.separator')}.WordMaster${System.getProperty('file.separator')}Database"
    static dataSource, sql

    static init() {
        def dir = new File(NAME)
        if(!dir.exists()) {
            create()
        }
    }
    
    static drop() {
        def dir = new File(NAME)
        if(dir.exists()) {
            def backupHome = NAME + '.bak'
            def bak = new File(backupHome)
            bak.mkdir()
            dir.renameTo(new File(backupHome, 'BAK' + new Date().getTime()))
        }
    }

    static getDataSource() {
        if(dataSource == null) {
            dataSource = new EmbeddedConnectionPoolDataSource40()
            dataSource.setDatabaseName(NAME)
        }

        dataSource
    }

    static getSql() {
        if(sql == null) {
            sql = new Sql(getDataSource())
        }

        sql
    }

    static execute(stmt) {
        getSql().execute(stmt)
    }

    static executeUpdate(stmt) {
        getSql().executeUpdate(stmt)
    }

    static executeInsert(stmt) {
        getSql().executeInsert(stmt)
    }

    static firstRow(stmt) {
        getSql().firstRow(stmt)
    }

    static eachRow(stmt, closure) {
        getSql().eachRow(stmt, closure)
    }

    // <editor-fold defaultstate="collapsed" desc=" Generated Code (by gRDB)">
    static create() {
        getDataSource().setCreateDatabase('create')
        
        PropertyIndex.createTable()
        
        Property.createTable()
        
        Word.createTable()
        
        Article.createTable()
        
        Category.createTable()
        
        CategoryIndex.createTable()
        
        Sentence.createTable()
        
        SentenceIndex.createTable()
        
        Review.createTable()
        
        ArticleText.createTable()
        
        WordIndex.createTable()
        
    }
    // </editor-fold>
}
